package com.lee.serviceagent.ocr.tesseract;

import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.opencv.global.opencv_imgcodecs;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.tesseract.TessBaseAPI;
import org.springframework.stereotype.Component;

import static org.bytedeco.opencv.global.opencv_imgproc.COLOR_BGR2GRAY;
import static org.bytedeco.opencv.global.opencv_imgproc.cvtColor;

/**
 * @author lee
 * @description class
 * @date 2025/8/19 上午10:30
 */
@Component
public class OCRService {

    public String doOCR(String imagePath) {
        TessBaseAPI tessBaseAPI = new TessBaseAPI();

        //初始化TessBaseAPI
        if (tessBaseAPI.Init(".", "ENG") != 0) {
            System.err.println("Could not initialize Tesseract.");
            return null;
        }

        //读取图像文件
        Mat image = opencv_imgcodecs.imread(imagePath);
        //图像预处理
        //如调整大小、转为灰度图等
        cvtColor(image, image, COLOR_BGR2GRAY);
        //设置图像
        int step = ((Long) image.step()).intValue();
        tessBaseAPI.SetImage(image.data(), image.cols(), image.rows(), 1, step);

        //设别文字
        BytePointer outText = tessBaseAPI.GetUTF8Text();
        String result = outText.getString();
        outText.deallocate();
        //释放资源
        tessBaseAPI.End();
        return result;
    }

    public String doOCR2(String imagePath) {
        TessBaseAPI tessBaseAPI = new TessBaseAPI();

        //初始化TessBaseAPI
        if (tessBaseAPI.Init(".", "ENG") != 0) {
            System.err.println("Could not initialize Tesseract.");
            return null;
        }

        ImagePreprocessing preprocessing = new ImagePreprocessing();
        Mat preprocessedImage = preprocessing.preprocessImage(imagePath);

        //设置图像
        int step = ((Long) preprocessedImage.step()).intValue();
        tessBaseAPI.SetImage(preprocessedImage.data(), preprocessedImage.cols(), preprocessedImage.rows(), 1, step);

        // 识别文字
        BytePointer outText = tessBaseAPI.GetUTF8Text();
        String result = outText.getString();
        outText.deallocate();
        // 释放资源
        tessBaseAPI.End();
        return result;
    }
}
